package blog

import (
	"encoding/json"
	"time"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/tag"
	"gitee.com/zatto/project/tree/master/vblog/api/validator"
)

func NewBlog(req *CreateBlogRequest) *Blog {
	now := time.Now()
	return &Blog{
		CreatedAt:         now.Unix(),
		UpdatedAt:         now.Unix(),
		CreateBlogRequest: req,
	}
}

type Blog struct {
	Id          int   `json:"id"`
	CreatedAt   int64 `json:"created_at"`
	UpdatedAt   int64 `json:"updated_at"`
	PublishedAt int64 `json:"published_at"`
	*CreateBlogRequest
	Tags []*tag.Tag `json:"tags"`
}

func NewCreateBlogRequest() *CreateBlogRequest {
	return &CreateBlogRequest{}
}

func (b *Blog) String() string {
	dj, err := json.Marshal(b)
	if err != nil {
		panic(err)
	}

	return string(dj)
}

type CreateBlogRequest struct {
	Title   string `json:"title" validate:"required"`
	Author  string `json:"author" validate:"required"`
	Summary string `json:"summary" validate:"required"`
	Context string `json:"context" validate:"required"`
	Status  Status `json:"status" `
}

func (req *CreateBlogRequest) Validate() error {
	return validator.V().Struct(req)
}

func NewBlogSet() *BlogSet {
	return &BlogSet{
		Items: []*Blog{},
	}
}

type BlogSet struct {
	// 文章总数
	Total int64 `json:"total"`
	// 文章列表
	Items []*Blog `json:"items"`
}

func (s *BlogSet) AddItem(item *Blog) {
	s.Items = append(s.Items, item)
}
